package com.ddd.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.cloud.netflix.zuul.util.ZuulRuntimeException;
import org.springframework.stereotype.Component;

/**
 * 捕捉zuul报错的过滤器
 * Created by zhouxj6112 on 2019/12/25.
 */
@Slf4j
@Component
public class ZuulErrorFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return FilterConstants.ERROR_TYPE;
    }

    @Override
    public int filterOrder() {
        // -2
        return FilterConstants.SEND_ERROR_FILTER_ORDER - 2;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        ZuulException exception = this.findZuulException(ctx.getThrowable());
        log.error("进入系统异常拦截", exception);

        ctx.setSendZuulResponse(false);
        ctx.getResponse().setContentType("text/html;charset=utf8");
        ctx.setResponseBody("{\"code\":-3,\"message\":\"网关服务异常\"}");

        return null;
    }

    private ZuulException findZuulException(Throwable throwable) {
        if (ZuulRuntimeException.class.isInstance(throwable.getCause())) {
            return (ZuulException)throwable.getCause().getCause();
        } else if (ZuulException.class.isInstance(throwable.getCause())) {
            return (ZuulException)throwable.getCause();
        } else {
            return ZuulException.class.isInstance(throwable) ? (ZuulException)throwable : new ZuulException(throwable, 500, (String)null);
        }
    }

}
